package advanced.network.basic_servlet;


import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 封装请求协议:
 * 获取method uri 以及请求协议
 */
public class Request {
    private static String CRTF = System.getProperty("line.separator");

    private String requestInfo;
    private String method;//请求的方法
    private String url;//请求url
    private String action;//action
    private Map<String, Object> params;//请求参数

    public Request(Socket client) throws IOException {
        this(client.getInputStream());
    }

    public Request(InputStream is) {
        byte[] datas = new byte[1024 * 1024];
        int len = 0;//读取了多少数据
        try {
            len = is.read(datas);
        } catch (IOException e) {
            e.printStackTrace();
        }
        requestInfo = new String(datas, 0, len);
        params = new HashMap<>();

        //分解字符串
        parserString();
    }

    /**
     * 解析请求头字串
     */
    private void parserString() {
        String[] split = requestInfo.split(" ");
        this.method = split[0];
        this.url = split[1];
        int pStart = (url.contains("?")) ? url.indexOf("?") : url.length();
        this.action = url.substring(url.indexOf(":8888") + 1, pStart);
        if (url.contains("?")) {//如果链接中包含参数
            String[] parmStr = url.split("\\?");
            if (parmStr.length > 1) {
                parseParam(parmStr[1]);
            }

        } else {
            String qStr = requestInfo.substring(this.requestInfo.lastIndexOf(CRTF)).trim();
            parseParam(qStr);
        }
    }

    /**
     * 获取参数
     *
     * @param key 参数名字
     * @return
     */
    public Object getParameter(String key) {
        return params.get(key);
    }

    /**
     * 解析传递的参数字符串
     *
     * @param paramStr
     */
    private void parseParam(String paramStr) {
        if (!paramStr.equals("")) {
            String[] ps = paramStr.split("&");
            for (String p : ps) {
                String[] kv = p.split("=");
                try {
                    params.put(kv[0], URLDecoder.decode(kv[1], "utf-8"));//
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    public String getMethod() {
        return method;
    }

    public String getUrl() {
        return url;
    }

    public String getAction() {
        return this.action;
    }

    @Override
    public String toString() {
        return "Request{" +
                "method='" + method + '\'' +
                ", url='" + url + '\'' +
                ", params=" + params +
                '}';
    }
}
